package shop_servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
public class LogoutServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            // 从会话中移除用户信息
            session.removeAttribute("user_id");
            // 销毁会话
            session.invalidate();
        }
        // 重定向到登录页面，使用URLEncoder对中文进行编码
        String encodedUrl = URLEncoder.encode("reg.jsp", "UTF-8");
        response.sendRedirect(request.getContextPath() + "/"+encodedUrl);
    }
}